import { AppConfig } from '@/utils/back/appConfig';
import { middleLogger } from '@/utils/back/devlogger';
import { redirectToLogin } from '@/utils/back/redirect';
import { pathsToRegs, tryParse } from '@/utils/common';
import { NextRequest, NextResponse } from 'next/server';

const passPaths = [
  '/maintain',
  '/healthcheck',
  '/api/configHook',
  '/api/configFile',
  '/api/test',
  '/api/login',
  '/nextasset',
  '/_next/image',
  '/_next/static/',
];

export default async function maintainMiddleware(req: NextRequest, next: Fn) {
  const pathname = req.nextUrl.pathname;
  // console.log('🚀 ~ maintainMiddleware ~ pathname:', pathname, req.url);

  const passPathRegs = pathsToRegs(passPaths);
  if (passPathRegs.some(reg => reg.test(pathname))) {
    return next(req);
  }

  const appConfig = await AppConfig.get(req.url);

  // console.log('🚀 ~ maintainMiddleware ~ appConfig:', appConfig, pathname);
  let shouldBlock = appConfig.isMaintainMode;

  const token = req.cookies.get('token')?.value || '';
  if (shouldBlock && appConfig.maintainPreviewUsers?.length > 0 && token) {
    const email = token ? tryParse(atob(token.split('.')[1]))?.email : '';
    shouldBlock = appConfig.maintainPreviewUsers.some((previewUser: string) =>
      (email || '').includes(previewUser.toLowerCase())
    );
  }

  return shouldBlock
    ? NextResponse.rewrite(new URL('/maintain', req.url))
    : next(req);
}
